package vip.xiaonuo.sys.core.init;

import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.context.constant.ConstantContext;
import vip.xiaonuo.core.enums.CommonStatusEnum;

import javax.sql.DataSource;
import java.util.List;

/**
 * @author yaorw
 */
@Component
@Order(1)
public class AppInitCommand implements CommandLineRunner {

    private static final Log log = Log.get();
    private static final String CONFIG_LIST_SQL = "select code,value from sys_config where status = ?";
    private static final String CAPITAL_CODE = "CODE";

    private static final String CODE = "code";

    private static final String CAPITAL_VALUE = "VALUE";

    private static final String VALUE = "value";

    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Autowired
    private Environment environment;

    @Override
    public void run(String... args) throws Exception {
        log.info("系统启用完成。加载全局变量>>>>>>>");
        String primary = environment.getProperty("spring.datasource.dynamic.primary");
        log.info("系统启用完成。加载全局变量 >>>>>>>  spring.datasource.dynamic.primary:{}", primary);
        DataSource source = dynamicRoutingDataSource.getCurrentDataSources().get(primary);
        // 获取sys_config表的数据
        List<Entity> entityList = SqlExecutor.query(source.getConnection(), CONFIG_LIST_SQL, new EntityListHandler(), CommonStatusEnum.ENABLE.getCode());

        // 将查询到的参数配置添加到缓存
        if (CollectionUtils.isNotEmpty(entityList)) {
            entityList.forEach(sysConfig -> {
                        String code = getOrDefault(sysConfig, CODE, CAPITAL_CODE);
                        String value = getOrDefault(sysConfig, VALUE, CAPITAL_VALUE);
                        ConstantContext.putConstant(code, value);
                    }

            );
        }
        log.info("系统启用完成。加载全局变量>>>>>>> {} 个", ConstantContext.me().size());
    }

    private String getOrDefault(Entity entity, String key, String defaultKey) {
        String v = entity.getStr(key);
        return StringUtils.isBlank(v) ? entity.getStr(defaultKey) : v;
    }
}
